<?php

namespace app\api\controller\order;

use app\api\model\common\CoinModel;
use app\api\model\order\OrderEarningModel;
use app\api\model\order\OrderMiningModel;
use app\api\model\user\UserAssetsLogModel;
use app\api\model\user\UserAssetsModel;
use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Log;

class OrderEarning extends Api
{
    protected $noNeedLogin = ['earning'];
    protected $noNeedRight = ['*'];

    /**
     * Notes: 矿机每天执行收益
     * User: 浪子膏
     * Date: 2023/10/31 21:54
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function earning()
    {
        $orderMiningModel = new OrderMiningModel();
        $list = $orderMiningModel->where('status', OrderMiningModel::STATUS_PAY)
            ->where('create_time', '<', strtotime(date('Y-m-d')))->select();

        $orderMiningModel->startTrans();
        try {
            $data = [];
            if (count($list) > 0) {
                foreach ($list as $key => $item) {
                    $coin = CoinModel::where('id', $item['coin_id'])->find();
                    if (empty($coin)) {
                        Log::write('订单' . $item['order_no'] . ' 没有查询到币种信息');
                        continue;
                    }
                    $orderEarningsModel = new OrderEarningModel();
                    if ($orderEarningsModel->where(['order_no' => $item['order_no'], 'earnings_date' => date('Y-m-d')])
                        ->count()) {
                        continue;
                    }
                    $electric_charge_day = round($item['electricity_bill'] * $item['power'] * 24 , 10);//当日电费
                    $price = round($item['computing_power'] * $coin['per_unit'], 10); // 每日挖矿收益
                    $real_price = $price - $electric_charge_day;
                    $data[] = [
                        'coin_id' => $coin['id'],
                        'coin_type' => strtolower($coin['coin_type']),
                        'user_id' => $item['user_id'],
                        'order_no' => $item['order_no'],
                        'electricity_bill' => $item['electricity_bill'],
                        'power' => $item['power'],
                        'electric_charge_day' => $electric_charge_day,
                        'computing_power' => $item['computing_power'],
                        'per_unit' => $coin['per_unit'],
                        'earnings_date' => date('Y-m-d'),
                        'price' => $price,
                        'real_price' => $real_price,
                    ];
                    $update['executed_day'] = $item['executed_day'] + 1;
                    if ($item['period'] != 0) {
                        if ($update['executed_day'] == $item['period']) {
                            $update['status'] = OrderMiningModel::STATUS_SU;
                        }
                        Db::name('order_mining')->where('order_no', $item['order_no'])->update($update);
                    }
                    switch ($coin['coin_type']) {
                        case 'BTC':
                            $field = 'btc';
                            break;
                        case 'BCH':
                            $field = 'bch';
                            break;
                        case 'LTC':
                            $field = 'ltc';
                            break;
                        case 'ETC':
                            $field = 'etc';
                            break;
                        case 'ZEC':
                            $field = 'zec';
                            break;
                        case 'DASH':
                            $field = 'dash';
                            break;
                    }
                    $userAssetsModel = new UserAssetsModel();
                    $userAssets = $userAssetsModel->where('user_id', $item['user_id'])->find();
                    $userAssets->$field = $userAssets->$field + $real_price;
                    $userAssets->save();

                    $userAssetsLogModel = new UserAssetsLogModel();
                    $userAssetsLogModel->createLog($field, $item['user_id'], $real_price,
                        UserAssetsLogModel::TYPE_MINING_PRICE, 1, $item['order_no']);

                }
                $orderEarningsModel->saveAll($data);
            }
            $orderMiningModel->commit();
        } catch (Exception $exception) {
            $orderMiningModel->rollback();
            Log::write($exception->getMessage());
        }

        $this->success('执行完毕-' . count($data));
    }
}